package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.UserBasicInfo;
import net.ib.mntalk.protocol.Session.GetBuddyInfosReq;
import net.ib.mntalk.protocol.Session.GetBuddyInfosRes;
import net.ib.mntalk.protocol.client.Database.ReceiverList;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class GetMemberInfosTask extends AsyncNetTask {
	
	private GetBuddyInfosReq getBuddyInfosReq;
	private long mClientViewUuidMsb;
	private long mClientViewUuidLsb;

	public GetMemberInfosTask(Context _context, Handler _uiHandler, long clientViewUuidMsb, long clientViewUuidLsb, GetBuddyInfosReq getBuddyInfosReq) {
		super(_context, _uiHandler);
		this.getBuddyInfosReq = getBuddyInfosReq;
		this.mClientViewUuidMsb = clientViewUuidMsb;
		this.mClientViewUuidLsb = clientViewUuidLsb;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(getBuddyInfosReq)
			.setMethodId(Session.Contact.GetBuddyInfos)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("GetMemberInfosTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		GetBuddyInfosRes getBuddyInfosRes = (GetBuddyInfosRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("GetMemberInfosTask ResponseCode : " + getBuddyInfosRes.getResponseCode());
		if(getBuddyInfosRes.getResponseCode() == Common.SUCCESS){
			// TODO : 
			ReceiverList receiverList = new ReceiverList();
			
			for(BuddyInfo info : getBuddyInfosRes.getBuddyInfoList()){
				UserBasicInfo userBasicInfo = new UserBasicInfo();
				userBasicInfo.setDisplayName(info.getName().getDisplayName());
				userBasicInfo.setUserUuid(info.getUserUuid());
				
				receiverList.addReceiver(userBasicInfo);
			}
			// DB에 멤버를 업데이트 한다.
			InboxDatabaseHelper.setMemberList(mContext, mClientViewUuidMsb, mClientViewUuidLsb, receiverList);
			
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_BUDDY_INFOS_FAIL));
		}
	}

}
